package com.lagou.test04.test01;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class StudentObjectStream {

    private static StudentService service = new StudentServiceImpl();

    //对象保存到文件中
    public static void studentOutputStream(List<Student> students){
        ObjectOutputStream outputStream = null;
        try {
            //对象输出流
            outputStream = new ObjectOutputStream(new FileOutputStream("G:/a.txt"));
            //对象写入
            outputStream.writeObject(students);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {

            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    //从文件中获取对象
    public static void studentInputStream(){

        FileInputStream fis = null;
        ObjectInputStream inputStream = null;
        try {
            //创建文件输入流
            fis = new FileInputStream("G:/a.txt");
            if (fis.read() == 0) {
                return;
            }

            inputStream = new ObjectInputStream(fis);
            //读取文件内容
            Object obj = inputStream.readObject();
            //对象强制类型转换
            List<Student> students = null;
            //如果文件内容为空，则对对象进行初始化
            if (obj == null) {
                students = new ArrayList<Student>();
            }
            
            students =( List<Student> )obj;
            service.setStudents(students);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }



        }
    }


}
